/**
 * 
 */
package org.rico.server;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author rico
 *
 */
public class LogoutServlet extends HttpServlet {
	private static final Logger logger = LoggerFactory.getLogger(LogoutServlet.class);
	
	private static Map<String, String> serverMap = new ConcurrentHashMap<>();

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = (String) req.getAttribute("username");
		String password = (String) req.getAttribute("password");
		String backUrl = (String) req.getAttribute("backUrl");
		
		boolean result = this.handleLogin(username, password);
		logger.info("server handle login[result={}, username={}, password={}]", new Object[]{result, username, password});
		
		String token = UUID.randomUUID().toString();
		this.handleResult(backUrl, token, resp);
		logger.info("handle result[backUrl={}]", backUrl);
	}
	
	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}
	
	/**
	 * @param username
	 * @param password
	 * @return
	 */
	private boolean handleLogin(String username, String password) {
		if("admin".equals(username) && "123456".equals(password)) {
			return true;
		}
		return false;
	}
	
	/**
	 * @param backUrl
	 * @param token
	 * @param resp
	 * @throws IOException
	 */
	private void handleResult(String backUrl, String token, HttpServletResponse resp) throws IOException {
		StringBuffer buff = new StringBuffer(backUrl);
		buff.append("?token=").append(token);
		resp.sendRedirect(buff.toString());
	}
}
